const http = require('http')
const spawn = require('child_process').spawn
const createHandler = require('github-webhook-handler')
const handler = createHandler({
  path: '/webhook',
  secret: 'inechowebhooK'
})

const SERVER_PORT = process.env.SERVER_PORT || 13344

http.createServer(function (req, res) {
  handler(req, res, function (err) {
    res.statusCode = 404
    res.end('Not found')
  })
}).listen(SERVER_PORT)

handler.on('error', function (err) {
  console.log('Error: ', err.message)
})

handler.on('push', function (event) {
  const {
    repository,
    ref,
    head_commit
  } = event.payload

  console.log('Received a push event for %s to %s', repository.name, ref)
  console.log('Commit message: %s', head_commit.message)

  if (head_commit.message.indexOf('[DEPLOY]') === 0) {
    console.log('Starting deploy updated.')

    runCommand('sh', ['./webhook/deploy.sh'], async function (s) {
      console.log(s)
    })
  }
})

function runCommand(cmd, args, callback) {
  const child = spawn(cmd, args)
  let s = ''

  child.stdout.on('data', function (buffer) {
    s += buffer.toString()
  })
  child.stdout.on('end', function () {
    callback(s)
  })
}
